package com.zyf.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zyf.common.lang.Result;
import com.zyf.common.loginDto.LoginDto;
import com.zyf.config.JwtFilter;
import com.zyf.config.JwtUtils;
import com.zyf.pojo.User;
import com.zyf.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    UserService service;

    @Resource
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",loginDto.getUsername());
        User one = service.getOne(wrapper);
        if(one == null)
            return Result.fail("用户名不正确");
//        Assert.notNull(one,"用户不存在");
        if(!one.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        String jwt = jwtUtils.generateToken(one.getId());
        response.setHeader("Authorization",jwt);
        response.setHeader("Access-control-Expose-Headers","Authorization");

        Map<Object, Object> map = MapUtil.builder().put("id", one.getId())
                .put("username", one.getUsername())
                .put("avater", one.getAvatar())
                .put("email", one.getEmail())
                .map();

        return Result.succ(map);
    }

    @GetMapping("/logout")
    public Result logout(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.succ(null);
    }
}
